<template>
  <current>
    <div class="common-container center-container flex flex-col h-full">
      <div class="common-header"><h3 class="common-header-title">成员管理</h3></div>
      <div class="common-content flex flex-1 flex-col">
        <div class="m-b-20 flex-bc">
          <div class="flex flex-items-center">
            <div class="all-wrap mr-10 flex-shrink-0">
              <span class="font-bold">所有成员</span>
              <span class="total-num">{{ pageObj.total }}</span>
            </div>
            <search-input v-model="nameInput" placeholder="输入成员名称精确查询" @search="search" />
          </div>
          <div>
            <el-button type="primary" @click="add">添加成员</el-button>
            <el-button type="danger" :disabled="selectData.length === 0" @click="batchDel"
              >批量移除</el-button
            >
          </div>
        </div>
        <div class="table-wrap ym-box flex-1">
          <ym-table
            v-loading="tableLoading"
            select-show
            class="no-selected"
            :data="tableData"
            :column-data="columnData"
            @selection-change="changeSelection"
          >
            <template #name="{ row }">
              <div>
                <div class="font-size-16 font-bold">{{ row.name }}</div>
                <div class="font-size-12 color-coolgray">加入时间：{{ row.createTime }}</div>
              </div>
            </template>
            <template #role="{ row }">
              <div>
                <el-tag>{{ row.roleName }}</el-tag>
              </div>
            </template>
            <template #operator="{ row }">
              <div class="operator-list">
                <el-icon @click="edit(row)">
                  <Edit />
                </el-icon>
                <el-icon @click="del(row)" class="remove">
                  <Close />
                </el-icon>
              </div>
            </template>
          </ym-table>
          <pagination
            v-model:currentPage="pageObj.pageNum"
            v-model:pageSize="pageObj.pageSize"
            :total="pageObj.total"
            @pagination="search"
          />
        </div>
      </div>
    </div>

    <dialog-view
      v-model:visible="dialogVisible"
      :title="dialogTitle"
      :save-loading="saveLoading"
      @cancel="cancel"
      @confirm="confirm"
      @close="close"
      :width="1100"
    >
      <el-form ref="formRef" :model="form" label-width="100px">
        <div class="center-list">
          <div class="flex" v-for="(member, index) in form.members" :key="member._id">
            <el-form-item
              label="成员"
              :prop="'members.' + index + '.uid'"
              :rules="{
                required: true,
                message: '请选择成员',
                trigger: 'change',
              }"
            >
              <select-form
                v-model="member.uid"
                :options="userOptions"
                :multiple="false"
                :default-props="{ label: 'name', value: 'uid' }"
              />
            </el-form-item>
            <el-form-item
              label="权限"
              :prop="'members.' + index + '.rid'"
              :rules="{
                required: true,
                message: '请选择权限',
                trigger: 'change',
              }"
            >
              <select-form
                v-model="member.rid"
                :options="roleOptions"
                :multiple="false"
                :default-props="{ label: 'name', value: 'rid' }"
              />
            </el-form-item>
            <el-form-item label="终止时间" :prop="'members.' + index + '.expDate'">
              <el-date-picker
                v-model="member.expDate"
                type="date"
                placeholder="请选择"
                style="width: 100%"
                value-format="YYYY-MM-DD hh:mm:ss"
              />
            </el-form-item>
            <div
              class="mb-18 ml-10 color-[--el-color-danger] flex cursor-pointer flex-items-center @hover:color-[--el-color-danger-light-3]"
            >
              <el-icon class="font-size-18" @click="removeCenter(index)"><Remove /></el-icon>
            </div>
          </div>
        </div>
        <div class="pl-100 mt-20">
          <el-button round size="small" @click="addCenter"
            ><el-icon class="mr-5"><Plus /></el-icon>添加成员</el-button
          >
        </div>
      </el-form>
    </dialog-view>
  </current>
</template>

<script lang="ts" setup>
import { reactive, Ref, ref, toRefs } from 'vue'
import { useRoute } from 'vue-router'

import SearchInput from '@/components/CommonSearch/SearchInput/index.vue'
import SelectForm from '@/components/Form/Select.vue'
import Current from '../../current/index.vue'

import RoleApi, { RoleType } from '@/api/backend/role'
import UserApi from '@/api/backend/user'
import ProjectMemberApi from '@/api/project/member'

import { commonHandle, DialogView, Pagination, YmTable } from '@/views/mixins/common'
import IBaseObj from '#/index'
import type { FormInstance } from 'element-plus'
import { nanoid } from 'nanoid'

const { pid } = useRoute().query

const { state, handleSearch, handleDelete, handleAdd, handleEdit, handleCancel, handleConfirm } =
  commonHandle()

const { pageObj, tableData, tableLoading, dialogVisible, dialogTitle, isAdd, saveLoading } =
  toRefs(state)

const columnData = [
  {
    label: '成员',
    prop: 'oid',
    slotname: 'name',
  },
  {
    label: '角色',
    prop: 'role',
    slotname: 'role',
  },
]

const nameInput = ref('')
const search = () => {
  handleSearch(ProjectMemberApi.queryMember, { pid, name: nameInput.value })
}

search()

const selectData: Ref<any[]> = ref([])
const changeSelection = (newSelection: any[]) => {
  selectData.value = newSelection
}
const batchDel = () => {
  console.log('s', selectData.value)
}

const add = () => {
  handleAdd('添加成员')
}
const edit = (row: IBaseObj) => {
  console.log(row)
  // handleEdit('编辑研究中心')
}
const del = (row: IBaseObj) => {
  console.log(row)
  handleDelete({
    url: ProjectMemberApi.delUrl,
    id: row.id,
    message: '确定移除该成员？',
    success: search,
  })
}

const formRef = ref<FormInstance>()
const form = reactive({
  members: [
    {
      _id: nanoid(),
      uid: '',
      rid: '',
      expDate: '',
    },
  ],
})

const cancel = () => {
  handleCancel()
}

const confirm = () => {
  formRef.value?.validate((valid: boolean) => {
    const params = form.members.map((v) => {
      return { ...v, pid, expDate: v.expDate }
    })
    handleConfirm({
      valid,
      addApi: ProjectMemberApi.batchSaveMember,
      params: { members: params },
      cb: () => {
        search()
        // 重新获取下拉框数据
        getUserData()
      },
    })
  })
}
const close = () => {
  formRef.value?.clearValidate()
  form.members = [
    {
      _id: nanoid(),
      uid: '',
      rid: '',
      expDate: '',
    },
  ]
}

const addCenter = () => {
  form.members.push({
    _id: nanoid(),
    uid: '',
    rid: '',
    expDate: '',
  })
}
const removeCenter = (index: number) => {
  form.members.splice(index, 1)
}

const userOptions = ref<IBaseObj[]>([])
const roleOptions = ref<IBaseObj[]>([])

const getUserData = async () => {
  userOptions.value = (await UserApi.getMemberList(pid as string)) || []
}
const getRoleData = async () => {
  roleOptions.value = (await RoleApi.getRoleList(RoleType.permission)) || []
}

getUserData()
getRoleData()

// const add = () => {
//   formRef.value?.validate(async (valid) => {
//     if (valid) {
//       addLoading.value = true
//       try {
//         console.log(form)
//         const params: IBaseObj[] = []
//         form.uid.forEach((uid: string | number) => {
//           params.push({
//             uid,
//             pid,
//             rid: form.rid,
//             expDate: form.expDate,
//           })
//         })
//         const ret = await ProjectApi.saveProjectMember(params)
//         if (ret) {
//           getProjectMemberList()
//         }
//       } finally {
//         addLoading.value = false
//       }
//     }
//   })
// }

// const delMember = (id: string | number) => {
//   handleDelete({
//     message: '确定删除该成员？',
//     url: ProjectApi.delMember,
//     id,
//     success: getProjectMemberList,
//   })
// }

// const changeRole = async ({ id, rid }: IBaseObj) => {
//   try {
//     await ProjectApi.updateMemberRole({ id, rid })
//   } finally {
//     getProjectMemberList()
//   }
// }

// const getProjectMemberList = () => {
//   handleSearch(ProjectApi.queryProjectMember, { pid })
// }
// getProjectMemberList()

// const formatTime = (startTime: number, endTime: number) => {
//   if (startTime && endTime) {
//     return parseTime(startTime, '{y}-{m}-{d}') + '至' + parseTime(endTime, '{y}-{m}-{d}')
//   }
//   return ''
// }
</script>

<style lang="scss" scoped>
.common-content {
  padding: 20px 0;
}
.common-card {
  padding: 16px;
  border: 1px solid #e5e5e5;
  background-color: #fafafa;
}
.org-member {
  margin-top: 20px;

  h4 {
    margin: 10px 0;
  }

  .common-card {
    padding: 0 0 16px;
  }

  .card-title {
    padding: 6px 16px;
    line-height: 36px;
    background-color: #fafafa;
    border-bottom: 1px solid #e5e5e5;
  }

  .total-num {
    position: relative;
    top: -4px;
    display: inline-block;
    height: 17px;
    margin-top: -5px;
    margin-left: 5px;
    line-height: 16px;
    padding: 1px 5px;
    border-radius: 50%;
    font-size: 12px;
    background-color: rgba(0, 0, 0, 0.07);
    color: #707070;
    text-align: center;
    vertical-align: baseline;
  }
}

.member-list {
  li {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 16px;
    border: 1px solid #f0f0f0;
    font-size: 14px;
    color: #2e2e2e;
    word-break: break-word;
  }
}

.org-info {
  line-height: 1.4;
  .name {
    margin-right: 4px;
    font-weight: bold;
  }

  .time {
    font-size: 12px;
  }
}

.right-operator {
  display: flex;
  align-items: center;
}

.bold {
  font-weight: bold;
}

.all-wrap {
  .total-num {
    position: relative;
    top: -4px;
    display: inline-block;
    height: 17px;
    margin-top: -5px;
    margin-left: 5px;
    line-height: 16px;
    padding: 1px 5px;
    border-radius: 50%;
    font-size: 12px;
    background-color: rgba(0, 0, 0, 0.07);
    color: #707070;
    text-align: center;
    vertical-align: baseline;
  }
}

.operator-list {
  display: flex;
  align-items: center;
  font-size: 18px;

  & > * {
    margin-right: 5px;
    cursor: pointer;

    &:hover {
      color: var(--color-primary);
    }
  }

  .remove {
    color: var(--el-color-danger);

    &:hover {
      color: var(--el-color-danger-light-3);
    }
  }

  svg {
    outline: none;
  }
}
</style>
